<template>
  <div class="wrapper">
    <LeftTree :height="treeHeight" :treeInfo="treeInfo" @nodeClick="nodeClick">
      <div>
        <div class="search">
          <el-input v-model="input" placeholder="请输入结构名称" size="medium"></el-input>
          <span class="btns">
            <el-button type="primary" size="small" icon="el-icon-search">查询</el-button>
            <el-button size="small" icon="el-icon-refresh">重置</el-button>
          </span>
        </div>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="openAdd"
                >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="multiDel">删除 </el-button>
            </el-col>
          </el-row>
        </div>
        <div>
          <Table
            :tableLabel="tableLabel"
            :tableData="tableData"
            :handleSelectionChange="handleSelectionChange"
            :handleDelete="handleDelete"
            :handleUpdate="handleUpdate"
          />
        </div>
      </div>
    </LeftTree>
    <Dialog
      :dialogVisible.sync="dialogVisible"
      :title="title"
      width="500px"
      @handleDialogVisible="handleDialogVisible"
      @handleCommit="handleCommit"
    >
      <el-form inline ref="form" :model="ruleForm" :rules="rules" label-width="70px">
        <el-form-item label="上级结构" prop="parentNo" label-width="80px">
          <TreeSelect
            :options="treeInfo"
            :props="defaultProps"
            width="300"
            :labelModel.sync="supStruct"
          />
        </el-form-item>
        <el-form-item
          label="结构名称"
          prop="storeName"
          class="move-bit"
          label-width="80px"
        >
          <el-input v-model="ruleForm.storeName" :style="'width: 300px'"></el-input>
        </el-form-item>
        <el-form-item
          label="结构图标"
          prop="storePic"
          class="change-pointer"
          label-width="80px"
        >
          <el-popover
            placement="bottom-start"
            width="460"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="iconSelected" />
            <el-input
              slot="reference"
              v-model="ruleForm.storePic"
              placeholder="点击选择图标"
              :style="'width: 300px'"
              readonly
            >
              <svg-icon
                v-if="ruleForm.storePic"
                slot="prefix"
                :icon-class="ruleForm.storePic"
                class="el-input__icon"
                style="height: 32px; width: 16px"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="备注" prop="mark" label-width="80px">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :style="'width: 300px;'"
          ></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import LeftTree from "@/components/LeftTree";
import Table from "@/components/Tables";
import Dialog from "@/components/Dialog";
import TreeSelect from "@/components/TreeSelect";
import IconSelect from "@/components/IconSelect";
import {
  getStorageTree,
  addFileStorage,
  getStorageList,
  removeHouse,
  editHouse
} from "@/api/warehouse/warehouse";

export default {
  components: {
    LeftTree,
    Table,
    Dialog,
    TreeSelect,
    IconSelect,
  },
  data() {
    return {
      treeHeight: "780px",
      treeInfo: [],
      input: "",
      title: "",
      tableLabel: [
        {
          prop: "orderNum",
          label: "序号",
          cancelSelection: false,
        },
        {
          prop: "storeName",
          label: "结构名称",
        },
        {
          prop: "supStruct",
          label: "上级结构",
        },
        {
          prop: "isOpera",
          label: "操作",
          isOpera: true,
          showUpdate: true,
          showDel: true,
        },
      ],
      dialogVisible: false,
      options: [
        {
          parentId: "0",
          id: "A",
          label: "label-A",
          children: [
            {
              parentId: "A",
              id: "A-1",
              label: "label-A-1",
            },
          ],
        },
        {
          parentId: "0",
          value: "B",
          label: "label-B",
          children: [],
        },
      ],
      selected: "",
      defaultProps: {
        parent: "parentNo", // 父级唯一标识
        value: "recNo", // 唯一标识
        label: "label", // 标签显示
        children: "children", // 子级
      },
      ruleForm: {
        parentNo: "",
        storeName: "",
        storePic: "",
        remark: "",
      },
      rules: {
        storeName: [{ required: true, message: "请输入结构名称", trigger: "change" }],
        parentNo: [{ required: true, message: "请选择上级结构", trigger: "change" }],
        storePic: [{ required: true, message: "请选择结构图标", trigger: "change" }],
      },
      tableData: [],
      supStruct: {},
      saveTreeSelect: {},
      selections: [],
      nodeCliked: {},
      status: 0
    };
  },
  methods: {
    nodeClick(treeChild) {
      this.nodeClicked = treeChild;
      this.getList(treeChild);
    },
    getList(treeObj) {
      if(treeObj) {
        getStorageList(treeObj.recNo).then((res) => {
          res.data.forEach((item) => (item.supStruct = treeObj.label));
          this.tableData = res.data;
          this.ruleForm.parentNo = treeObj.recNo;
          this.saveTreeSelect = { recNo: treeObj.recNo, label: treeObj.label, level: treeObj.level, parentNo: treeObj.parentNo };
          this.supStruct = { recNo: treeObj.recNo, label: treeObj.label, level: treeObj.level, parentNo: treeObj.parentNo };
        });
      }
    },
    openAdd() {
      this.title = "新增结构";
      this.status = 0;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    handleDialogVisible() {
      this.dialogVisible = false;
      this.clear();
      this.supStruct = this.saveTreeSelect;
    },
    clear() {
      for(const i in this.ruleForm) {
        this.ruleForm[i] = null;
      }
    },
    getTree() {
      getStorageTree().then((res) => {
        this.treeInfo = res.data;
      });
    },
    handleCommit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const newForm = { ...this.ruleForm };
          const sorted = this.tableData.sort((a, b) => b.orderNum - a.orderNum);
          if(this.status === 0) {
            if (this.tableData.length > 0) {
              newForm.orderNum = sorted[0].orderNum - -1;
            } else {
              const serial = await getStorageList(this.ruleForm.parentNo);
              const sort = serial.data.sort((a, b) => b.orderNum - a.orderNum);
              if(sort.length > 0) {
                newForm.orderNum = sort[0].orderNum + 1;
              } else {
                newForm.orderNum = 1;
              }
            }
            newForm.parentNo = this.ruleForm.parentNo;
            
            addFileStorage(newForm).then((res) => {
              this.dialogVisible = false;
              this.getTree();
              this.clear();
              this.getList(this.nodeClicked);
            });
          } else if(this.status === 1) {
            editHouse(this.ruleForm).then(res => {
              if(res.code===200) {
                this.getList(this.nodeClicked);
                this.getTree();
                this.clear();
                this.dialogVisible = false;
              }
            })
          }
        }
      });
    },
    iconSelected(name) {
      this.ruleForm.storePic = name;
    },
    //存取删除所需recNo
    handleSelectionChange(selections) {
      this.selections = selections.map((item) => item.recNo);
    },
    //删除行
    handleDelete(selected) {
       this.$confirm('此操作将删除该选项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeHouse([selected.recNo].toString()).then(res => {
            if(res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList(this.nodeClicked);
              this.getTree();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //多选删除
    multiDel() {
      if(this.selections.length>0) {
        this.$confirm('此操作将删除所选选项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeHouse(this.selections.toString()).then(res => {
            if(res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList(this.nodeClicked);
              this.getTree();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    //修改行
    handleUpdate(row) {
      this.title = "修改结构";
      this.status = 1;
      for(const i in row) {
        this.ruleForm[i] = row[i];
      }
      this.dialogVisible = true;
    }
  },
  created() {
    this.getTree();
  },
  watch: {
    supStruct: {
      deep: true,
      handler() {
        this.ruleForm.parentNo = this.supStruct.recNo;
      },
    },
  },
};
</script>

<style scoped lang="scss">
.wrapper {
  padding: 30px;
}

::v-deep .search .el-input {
  width: 200px;
}

.search {
  margin-bottom: 10px;
}

.btns {
  margin-left: 20px;
}
::v-deep .el-dialog__body {
  box-sizing: border-box;
  padding-left: 50px;
}
.move-bit {
  margin-top: -13px;
}
::v-deep .el-textarea__inner {
  resize: none;
  height: 100px;
}
::v-deep .change-pointer .el-form-item__content .el-input--medium input {
  cursor: pointer;
}
</style>
